echo "-----------正在安装docker访问安全证书----------"
#以下是参数信息
#--[BEGIN]-------------
CODE="docker"
#第一个参数:IP地址(本机地址)
IP=$1
#第二个参数:密码(本机SSH连接的密钥)
PASSWORD=$2
# 国家
COUNTRY="CN"
# 城市
CITY="GUANGZHOU"
# 组织
ORGANIZATION="SCAU"
# 组织单元
ORGANIZATIONAL_UNIT="VM"
# 通用名
COMMON_NAME="$IP"
# 邮箱:这里的话暂时用我的邮箱,以后可以修改
EMAIL="1274356440@qq.com"
#--[END]------
mkdir /usr/local/docker-ca || cd /usr/local/docker-ca
# 1.生成CA密钥
openssl genrsa -aes256 -passout "pass:$PASSWORD" -out "ca-key-$CODE.pem" 4096
# 2.处理CA
openssl req -new -x509 -days 365 -key "ca-key-$CODE.pem" -sha256 -out "ca-$CODE.pem" -passin "pass:$PASSWORD" -subj "/C=$COUNTRY/ST=$STATE/L=$CITY/O=$ORGANIZATION/OU=$ORGANIZATIONAL_UNIT/CN=$COMMON_NAME/emailAddress=$EMAIL"
# 3.生成CA服务端密钥
openssl genrsa -out "server-key-$CODE.pem" 4096
# 4.生成CA服务端证书
openssl req -subj "/CN=$COMMON_NAME" -sha256 -new -key "server-key-$CODE.pem" -out server.csr
echo "subjectAltName = IP:$IP,IP:127.0.0.1" >> extfile.cnf
echo "extendedKeyUsage = serverAuth" >> extfile.cnf
openssl x509 -req -days 365 -sha256 -in server.csr -passin "pass:$PASSWORD" -CA "ca-$CODE.pem" -CAkey "ca-key-$CODE.pem" -CAcreateserial -out "server-cert-$CODE.pem" -extfile extfile.cnf
# 5. 删除无关文件
rm -f extfile.cnf
openssl genrsa -out "key-$CODE.pem" 4096
openssl req -subj '/CN=client' -new -key "key-$CODE.pem" -out client.csr
echo extendedKeyUsage = clientAuth >> extfile.cnf
openssl x509 -req -days 365 -sha256 -in client.csr -passin "pass:$PASSWORD" -CA "ca-$CODE.pem" -CAkey "ca-key-$CODE.pem" -CAcreateserial -out "cert-$CODE.pem" -extfile extfile.cnf
rm -vf client.csr server.csr
chmod -v 0400 "ca-key-$CODE.pem" "key-$CODE.pem" "server-key-$CODE.pem"
chmod -v 0444 "ca-$CODE.pem" "server-cert-$CODE.pem" "cert-$CODE.pem"
# 6. 打包客户端的证书
mkdir -p "tls-client-certs-$CODE"
cp -f "ca-$CODE.pem" "cert-$CODE.pem" "key-$CODE.pem" "tls-client-certs-$CODE/"
cd "tls-client-certs-$CODE"
tar zcf "tls-client-certs-$CODE.tar.gz" *
mv "tls-client-certs-$CODE.tar.gz" ../
cd ..
rm -rf "tls-client-certs-$CODE"
# 7. 拷贝服务端证书
mkdir -p /etc/docker/certs.d
cp "ca-$CODE.pem" "server-cert-$CODE.pem" "server-key-$CODE.pem" /etc/docker/certs.d/
# 8. 添加端口验证:默认使用2375但是使用了加密的方法
sudo tee /usr/lib/systemd/system/docker.service <<-'EOF'
[Service]
ExecStart=/usr/bin/dockerd --tlsverify --tlscacert=/usr/local/docker-ca/ca-docker.pem --tlscert=/usr/local/docker-ca/server-cert-docker.pem --tlskey=/usr/local/docker-ca/server-key-docker.pem -H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock
EOF
systemctl daemon-reload && systemctl restart docker
service docker restart
echo "正在开放端口"
#docker远程端口
firewall-cmd --zone=public --add-port=2375/tcp --permanent
#dubbo暴露端口
firewall-cmd --zone=public --add-port=20880/tcp --permanent
firewall-cmd --reload
# 将文件部署到指定的位置
mkdir /usr/local/docker-ca-copy
tar -xvf tls-client-certs-docker.tar.gz -C /usr/local/docker-ca-copy
cd /usr/local/docker-ca-copy
# 更换名字
mv ca-docker.pem ca.pem
mv cert-docker.pem cert.pem
mv key-docker.pem key.pem
echo "CAz证书文件已经部署到指定的位置"